package com.applications.codemash.core.eventhandlers;

import com.applications.codemash.core.Constants;
import com.applications.codemash.core.Session;
import com.applications.codemash.core.SessionNotificationAlarmReceiver;
import com.applications.codemash.utility.CustomContext;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class SessionNotifyCheckChangeListener implements
		OnCheckedChangeListener
{
	private String _sessionUri;
	private Activity _activity;
	
	public SessionNotifyCheckChangeListener(String sessionUri, Activity activity)
	{
		_sessionUri = sessionUri;
		_activity = activity;
	}
	
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
	{
		AlarmManager am = (AlarmManager)_activity.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(_activity, SessionNotificationAlarmReceiver.class);
		
		Session localSession = CustomContext.getSessionCache().GetSessionBySessionUri(_sessionUri);
		localSession.setNotifyOnStart(isChecked);
		
		intent.putExtra(Constants.SESSION_INTENT_KEY, localSession);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(_activity, localSession.getNotificationId(),
				intent, PendingIntent.FLAG_UPDATE_CURRENT);
		CustomContext.getDbAdapter().UpdateSession(localSession.getSessionUri(), isChecked);
		
		if (isChecked)
		{
			am.set(AlarmManager.RTC_WAKEUP, localSession.getStart().getTime(), pendingIntent);
			Toast.makeText(_activity, com.applications.codemash.R.string.notificationSetText, Toast.LENGTH_SHORT).show();
		}
		else
		{
			am.cancel(pendingIntent);
			Toast.makeText(_activity, com.applications.codemash.R.string.notificationUnsetText, Toast.LENGTH_SHORT).show();
		}
	}

}
